#include <iostream>
#include <unistd.h>
#include <cassert>
#include <string>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
int main()
{
    //第一步，打开读写端
    int fds[2];
    int n = pipe(fds);
    assert(n==0);
    //创建子进程
    pid_t id = fork();
    assert(id >= 0);
    if(id == 0)
    {
        //子进程写，关闭读端
        close(fds[0]);
        //子进程写入
        int cnt = 0;
        while(1)
        {
            char buffer[1024];
            snprintf(buffer,sizeof buffer,"我是子进程，向父进程写入：%d id:%d",cnt++,getpid());
            //通过write写入
            write(fds[1],buffer,sizeof buffer);
            sleep(1);
            //break;
        }
        //子进程关闭写端
        close(fds[1]);
        cout<<"子进程关闭写端"<<endl;
        exit(0);
    }
    //父进程读子进程的数据
    close(fds[1]);
    while(1)
    {
        sleep(2);
        char buffer[1024];
        ssize_t s = read(fds[0],buffer,sizeof(buffer));
        if(s>0)
        {
            buffer[s] = 0;
            //向屏幕输出
            cout<<"父进程接受信号："<<buffer<<endl;
        }
        else if(s == 0)
        {
            //读到文件结尾,读不到会阻塞等待
            cout<<"read :"<<s<<endl;
        }
        break;
    }
    //父进程关闭读端
    close(fds[0]);
    cout<<"父进程关闭读端"<<endl;
    //子进程退出，父进程回收
    int status = 0;
    n = waitpid(id,&status,0);
    assert(n == id);
    cout<<"pid:"<<n<<(status & 0x7F)<<endl;
    return 0;
}